package cn.senjoeson.triper.adapter;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;

import java.util.List;

import cn.senjoeson.triper.R;
import cn.senjoeson.triper.base.GreenDaoManager;
import cn.senjoeson.triper.bean.HistoryBean;
import cn.senjoeson.triper.dao.HistoryBeanDao;

/**
 * @author Android
 * @date 2018/1/8
 */

public class SearchTagAdapter extends TagAdapter<HistoryBean> {

    private List<HistoryBean> mHistoryBeans;

    public SearchTagAdapter(List<HistoryBean> datas) {
        super(datas);
        this.mHistoryBeans = datas;
    }

    @Override
    public View getView(FlowLayout parent, int position, final HistoryBean historyBean) {
        View view = View.inflate(parent.getContext(), R.layout.search_item, null);
        TextView mSearchContent = view.findViewById(R.id.searchContent);
        final ImageView mDelete = view.findViewById(R.id.search_delete);
        mSearchContent.setText(historyBean.getContent());

        mSearchContent.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mDelete.setVisibility(View.VISIBLE);
                return true;
            }
        });
        mDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteItem(historyBean);
            }
        });
        return view;
    }


    private void deleteItem(HistoryBean historyBean) {
        HistoryBeanDao historyBeanDao = GreenDaoManager.getInstance().getNewSession().getHistoryBeanDao();
        if (mHistoryBeans.contains(historyBean)) {
            mHistoryBeans.remove(historyBean);
            notifyDataChanged();
            historyBeanDao.deleteByKey(historyBean.getHistoryid());
        }
    }
}
